// Copyright 2024 Tvux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package _003

func lengthOfLongestSubstring(s string) (res int) {
	// 使用滑动窗口
	window := make(map[byte]struct{}, len(s))
	left := 0
	for right, ch := range s {
		// 如果窗口中已经存在当前字符，就将窗口的左边界向右移动，直到窗口中不再存在当前字符
		for {
			_, ok := window[byte(ch)]
			if ok {
				delete(window, s[left])
				left++
			} else {
				break
			}
		}
		// 将当前字符加入窗口
		window[byte(ch)] = struct{}{}
		// 更新最大长度
		res = max(res, right-left+1)
	}
	return res
}
